package xyz.coolcsm.security.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.coolcsm.security.config.JsonResult;
import xyz.coolcsm.security.config.ResultTool;
import xyz.coolcsm.security.config.RsaKeyProperties;
import xyz.coolcsm.security.entity.*;
import xyz.coolcsm.security.service.*;
import xyz.coolcsm.security.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 什锦
 * @since 2021-06-1
 */

@RestController
public class BlogController {
    @Autowired
    private RsaKeyProperties prop;

    @Autowired
    BlogService blogService;

    @Autowired
    BlogCategoryService blogCategoryService;

    @Autowired
    CommentService commentService;

    @Autowired
    FavoriteService favoriteService;

    @Autowired
    RedisService redisService;


    //个人的博客分页
    @GetMapping("/api/blog/{limit}/{page}")
    public JsonResult blogListPage(HttpServletRequest request,@PathVariable("page") int page, @PathVariable("limit") int limit){
        //解析token获取用户信息
        Payload<SysUser> payload = null;
        String token = request.getHeader("Authorization");
        payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                prop.getPublicKey(), SysUser.class);
        //先从缓存中查询
        String key = "redis:blog:" +page+payload.getUserInfo().getId();
        Object object = redisService.get(key);
        //缓存不存在，从数据库查询，并存入redis
        if (object == null){
            Page<Blog> pageParam = new Page<>(page, limit);
            blogService.page(pageParam,new QueryWrapper<Blog>().eq("author_id",payload.getUserInfo().getId())
                    .orderByDesc("create_time"));
            redisService.set(key,pageParam,60*60);
            return ResultTool.success(pageParam);
        }
        //存在，直接查询并返回
        Page<Blog> pageParam = (Page<Blog>)object;
        return ResultTool.success(pageParam);
    }


    //首页分类博客管理
    @GetMapping("/api/blog/{limit}/{page}/{cid}")
    public JsonResult blogListPageByCid(@PathVariable("page") int page, @PathVariable("limit") int limit,
                                       @PathVariable("cid") int cid){
        //先从缓存中查询
        String key = "redis:blogByCid:" +page + "to" +cid;
        Object object = redisService.get(key);
        //缓存不存在，从数据库查询，并存入redis
        if (object == null){
            Page<Blog> blogPage = blogService.pageByCid(page, limit, cid);
            redisService.set(key,blogPage,5*60);
            return ResultTool.success(blogPage);
        }
        Page<Blog> blogPage = (Page<Blog>)object;
        return ResultTool.success(blogPage);
    }



    //博客详情
    @GetMapping("/api/blog/details/{id}")
    public JsonResult blogDetails(@PathVariable("id") int id){
        //先从缓存中查询
        String key = "redis:blogDetails:" +id;
        Object object = redisService.get(key);
        //缓存不存在，去数据库获取，更新浏览量，并存入redis
        if (object == null){
            Blog blog = blogService.getById(id);
            int i = blog.getViews() + 1;
            blog.setViews(i);
            blogService.updateById(blog);
            redisService.set(key,blog);
            return ResultTool.success(blog);
        }
        //存在，更新浏览量
        Blog blog = (Blog)object;
        int i = blog.getViews() + 1;
        blog.setViews(i);
        blogService.updateById(blog);
        redisService.set(key,blog);
        return ResultTool.success(blog);
    }

    //删除博客
    @DeleteMapping("/api/user/blog/delete/{bid}")
    public JsonResult delete(HttpServletRequest request,@PathVariable("bid") String bid){
        //获取用户信息
        String token = request.getHeader("Authorization");
        Payload<SysUser> payload = null;
        payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                prop.getPublicKey(), SysUser.class);
        //先删除缓存
        String key2 = "redis:blogDetails:" +bid;
        redisService.del(key2);
        for (int i = 1;i<100;i++){
            String key = "redis:blog:" +i+payload.getUserInfo().getId();
            redisService.del(key);
            for (int x = 0;i<10;i++){
                String key1 = "redis:blogByCid:" +i + "to" +x;
                redisService.del(key1);
            }
        }
        //删除博客
        Boolean flag =blogService.remove(new QueryWrapper<Blog>().eq("id", bid).eq("author_id",payload.getUserInfo().getId()));
        if ( flag == false){
            return ResultTool.fail();
        }
        //删除成功，再一次删除缓存，避免脏数据
        commentService.remove(new QueryWrapper<Comment>().eq("qid",bid).eq("topic_category","2"));
        redisService.del(key2);
        for (int i = 1;i<100;i++){
            String key = "redis:blog:" +i+payload.getUserInfo().getId();
            redisService.del(key);
            for (int x = 0;i<10;i++){
                String key1 = "redis:blogByCid:" +i + "to" +x;
                redisService.del(key1);
            }
        }
        return ResultTool.success();
    }

    //博客分类
    @GetMapping("/api/blog/blogCategory")
    public JsonResult blogCategory(){
        String key = "redis:blogCategory:" +1;
        Object object = redisService.get(key);
        if (object == null){
            List<BlogCategory> list = blogCategoryService.list();
            redisService.set(key,list);
            return ResultTool.success(list);
        }
        List<BlogCategory> list = (List<BlogCategory>)object;
        return ResultTool.success(list);
    }

    //博客新增或修改
    @PostMapping("/api/blog/issueBlog")
    public JsonResult issueQuestion(HttpServletRequest request, @RequestBody Blog blog ){
        //获取个人信息
        String token = request.getHeader("Authorization");
        Payload<SysUser> payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                        prop.getPublicKey(), SysUser.class);
        SysUser user = payload.getUserInfo();
        if (blog.getId() != null){
            String key2 = "redis:blogDetails:" +blog.getId();
            redisService.del(key2);
        }
        //先清除个人博客缓存和首页博客列表缓存
        for (int i = 1;i<100;i++){
            String key = "redis:blog:" +i+payload.getUserInfo().getId();
            redisService.del(key);
            for (int x = 0;i<10;i++){
                String key1 = "redis:blogByCid:" +i + "to" +x;
                redisService.del(key1);
            }
        }
        blog.setAuthorId(user.getId().toString());
        blog.setAuthorAvatar(user.getAvatar());
        blog.setAuthorName(user.getNickName());
        blogService.saveOrUpdate(blog);
        if (blog.getId() != null){
            String key2 = "redis:blogDetails:" +blog.getId();
            redisService.del(key2);
        }
        //在一清楚，防止脏数据
        for (int i = 1;i<100;i++){
            String key = "redis:blog:" +i+payload.getUserInfo().getId();
            redisService.del(key);
            for (int x = 0;i<10;i++){
                String key1 = "redis:blogByCid:" +i + "to" +x;
                redisService.del(key1);
            }
        }

        return ResultTool.success();
    }

    //添加收藏
    @PutMapping("/api/blog/{bid}/favorite")
    public JsonResult addFavorite(HttpServletRequest request,@PathVariable("bid") Integer bid){
        //获取个人信息
        String token = request.getHeader("Authorization");
        Payload<SysUser> payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                prop.getPublicKey(), SysUser.class);
        for (int i = 1;i<100;i++){
            String key = "redis:blogFavorite:" + i + payload.getUserInfo().getId();
            redisService.del(key);
        }
        //创建对象，添加收藏
        Favorite favorite = new Favorite();
        favorite.setBid(bid);
        favorite.setUid(payload.getUserInfo().getId());
        //在一次删除缓存，避免脏数据
        favoriteService.save(favorite);
        for (int i = 1;i<100;i++){
            String key = "redis:blogFavorite:" + i + payload.getUserInfo().getId();
            redisService.del(key);
        }
        return ResultTool.success();
    }

    //是否为收藏
    @GetMapping("/api/blog/{bid}/favorite")
    public JsonResult isFavorite(HttpServletRequest request,@PathVariable("bid") Integer bid){
        //获取个人信息
        String token = request.getHeader("Authorization");
        Payload<SysUser> payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                prop.getPublicKey(), SysUser.class);
        Favorite one = favoriteService.getOne(new QueryWrapper<Favorite>().eq("bid", bid).eq("uid", payload.getUserInfo().getId()));
        //为空表示
        if (one == null){
            return ResultTool.fail();
        }
        return ResultTool.success();
    }

    //删除收藏
    @DeleteMapping("/api/blog/delete/{bid}")
    public JsonResult deleteFavorite(HttpServletRequest request,@PathVariable("bid") Integer bid){
        //获取个人信息
        String token = request.getHeader("Authorization");
        Payload<SysUser> payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                prop.getPublicKey(), SysUser.class);
        //删除缓存
        for (int i = 1;i<100;i++){
            String key = "redis:blogFavorite:" + i + payload.getUserInfo().getId();
            redisService.del(key);
        }
        Boolean flag = favoriteService.remove(new QueryWrapper<Favorite>().eq("bid", bid).eq("uid", payload.getUserInfo().getId()));
        if (flag == false){
            return ResultTool.fail();
        }
        for (int i = 1;i<100;i++){
            String key = "redis:blogFavorite:" + i + payload.getUserInfo().getId();
            redisService.del(key);
        }
        return ResultTool.success();
    }

    //收藏分页管理
    @GetMapping("/api/blog/favorite/{limit}/{page}")
    public JsonResult listFavoriteBlogByUser(HttpServletRequest request,@PathVariable("limit") Integer limit,@PathVariable("page") Integer page){
        String token = request.getHeader("Authorization");
        Payload<SysUser> payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                prop.getPublicKey(), SysUser.class);
        String key = "redis:blogFavorite:" + page+payload.getUserInfo().getId();
        Object object = redisService.get(key);
        if (object == null){
            List<Favorite> uid = favoriteService.list(new QueryWrapper<Favorite>().eq("uid", payload.getUserInfo().getId()));
            PageBean<Blog> blogList = blogService.getBlogList(uid, page, limit);
            redisService.set(key,blogList,5*60);
            return ResultTool.success(blogList);
        }
        PageBean<Blog> blogList = (PageBean<Blog>)object;
        return ResultTool.success(blogList);
    }



}
